<?php

use console\db\Migration;
use yii\helpers\ArrayHelper;
use yii\db\Query;

/**
 * 用户证件号加密
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300000_000014_t_user_authent_encrypt extends Migration {

    const BATCH_SIZE = 1000;

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user_authent}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)->select([
            'id',
            'idcardno',
        ])->where([
            'and',
            ['!=', 'idcardno', ''],
            ['idcardno_hash' => null]
        ]);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        foreach ($rows as $user) {
            $columns = static::encryptData($user['idcardno']);
            $migration->db->createCommand()->update($migration->tableName, $columns, [
                'id' => $user['id']
            ])->execute();
        }
    }

    /**
     * 加密身份证
     * @param string $idcardno
     */
    private static function encryptData($idcardno) {
        if ($idcardno) {
            /* @var $security \common\base\Security */
            $security = Yii::$app->security;
            return [
                'idcardno' => $security->generatePrivateKey($idcardno),
                'idcardno_hash' => $security->encryptMaster($idcardno),
            ];
        }
        return [
            'idcardno' => '',
            'idcardno_hash' => null,
        ];
    }

}
